#include "delay.h"

void delay_config_us(void){
    
    timer_parameter_struct timer_initpara;

    rcu_periph_clock_enable(DELAY_TIMER_RCU);
    timer_deinit(DELAY_TIMER);

    /* TIMER configuration */
    timer_initpara.prescaler         = 4 - 1;
    timer_initpara.alignedmode       = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection  = TIMER_COUNTER_UP;
    timer_initpara.period            = 18 - 1;
    timer_initpara.clockdivision     = TIMER_CKDIV_DIV1;
    timer_initpara.repetitioncounter = 0;
    timer_init(DELAY_TIMER,&timer_initpara);
    
    /* auto-reload preload enable */
    timer_auto_reload_shadow_enable(DELAY_TIMER);
}

void delay_config_iic(void){
    
    timer_parameter_struct timer_initpara;

    rcu_periph_clock_enable(DELAY_TIMER_RCU);
    timer_deinit(DELAY_TIMER);

    /* TIMER configuration */
    timer_initpara.prescaler         = 4 - 1;
    timer_initpara.alignedmode       = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection  = TIMER_COUNTER_UP;
    timer_initpara.period            = 6 - 1;
    timer_initpara.clockdivision     = TIMER_CKDIV_DIV1;
    timer_initpara.repetitioncounter = 0;
    timer_init(DELAY_TIMER,&timer_initpara);
    
    /* auto-reload preload enable */
    timer_auto_reload_shadow_enable(DELAY_TIMER);
}

void delay_us(uint16_t us){
    timer_enable(DELAY_TIMER);
    while (us--)
    {
        while (timer_flag_get(DELAY_TIMER, TIMER_FLAG_UP) == RESET);
        timer_flag_clear(DELAY_TIMER, TIMER_FLAG_UP);
    }
    timer_disable(DELAY_TIMER);
}
void delay_iic(){
    timer_enable(DELAY_TIMER);
    while (timer_flag_get(DELAY_TIMER, TIMER_FLAG_UP) == RESET);
    timer_flag_clear(DELAY_TIMER, TIMER_FLAG_UP);
    timer_disable(DELAY_TIMER);
}

void delay_iic_hight(){
    timer_enable(DELAY_TIMER);
    uint8_t time = 2;
    while (time--)
    {
        while (timer_flag_get(DELAY_TIMER, TIMER_FLAG_UP) == RESET);
        timer_flag_clear(DELAY_TIMER, TIMER_FLAG_UP);
    }
    timer_disable(DELAY_TIMER);
}
